package lib.okhttp3;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSON;

import okhttp3.*;


public class OkHttpConfig {

    public static SSLSocketFactory sslSocketFactory() throws CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException {
        try {
        	KeyStore keyStore = KeyStore.getInstance("PKCS12");
        	keyStore.load(new FileInputStream(new File("C:\\Users\\18811\\Desktop\\client.p12")), "123456".toCharArray());
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, "123456".toCharArray());
            //信任任何链接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagerFactory.getKeyManagers(), getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
			e.printStackTrace();
		}
        return null;
    }
    /**
     * Create a new connection pool with tuning parameters appropriate for a single-user application.
     * The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
     */
    public static ConnectionPool pool() {
        return new ConnectionPool(200, 5, TimeUnit.MINUTES);
    }
    
    public static OkHttpClient okHttpClient() throws UnrecoverableKeyException, CertificateException, FileNotFoundException, IOException {
        return new OkHttpClient.Builder()
                .sslSocketFactory(sslSocketFactory())
                .hostnameVerifier(getHostnameVerifier())
                //是否开启缓存
                .retryOnConnectionFailure(true)
                //连接池
                .connectionPool(pool())
                .connectTimeout(3L, TimeUnit.SECONDS)
                .readTimeout(3L, TimeUnit.SECONDS)
                .build();
    }
    
    public static void main(String[] args) throws UnrecoverableKeyException, CertificateException, FileNotFoundException, IOException {
    	String jsonStr = "报警数据";
    	
    	JSONArray json = JSON.parseArray(jsonStr);
    	Request.Builder builder = new Request.Builder().url("接口地址").post(RequestBody.create(null, json.toJSONString()));
    
    	builder.addHeader("From", "Y");
    	builder.addHeader("Content-Type", "application/json");
    	
    	Request request = builder.build();
    	Response response = okHttpClient().newCall(request).execute();
    	System.out.println(response.body().string());
	}
    
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
 
    /**
     * 获取trustManager
     *
     * @return
     */
    public static TrustManager[] getTrustManager() {
        TrustManager[] trustManager = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }
 
                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }
 
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustManager;
    }
 
    /**
     * 获取hostnameVerifier
     *
     * @return
     */
    public static HostnameVerifier getHostnameVerifier() {
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        };
        return hostnameVerifier;
    }

}
